/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import BUSServices.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author USER
 */
public class HoaDonBanSach extends javax.swing.JDialog {

    /**
     * Creates new form HoaDon
     */
    DefaultTableModel tableModel;
    private List<Sach> gioHang;
    BUSServices.QLNSBUSWebService_Service service;
    BUSServices.QLNSBUSWebService port;

    public HoaDonBanSach(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        //Khởi tạo services và gọi services.
        service = new BUSServices.QLNSBUSWebService_Service();
        port = service.getQLNSBUSWebServicePort();

        gioHang = new ArrayList<Sach>();

        this.tableModel = new DefaultTableModel();
        this.tableModel.addColumn("STT");
        this.tableModel.addColumn("Mã sách");
        this.tableModel.addColumn("Tên sách");
        this.tableModel.addColumn("Giá bán");
        this.tableModel.addColumn("Số lượng bán");
        this.tableModel.addColumn("Thành tiền");

        this.jtblSach.setModel(tableModel);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jtfTenNhanVien = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jtfNgayLapHD = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtblSach = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        jtfTongTien = new javax.swing.JTextField();
        jbtChonSach = new javax.swing.JButton();
        jbtThanhToan = new javax.swing.JButton();
        jbtThoat = new javax.swing.JButton();
        jbtHuy = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setText("Tên nhân viên:");

        jLabel2.setText("Ngày lập hóa đơn:");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Chi tiết hóa đơn"));

        jtblSach.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtblSach);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jLabel3.setText("Tổng tiền:");

        jbtChonSach.setText("Chọn sách");
        jbtChonSach.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtChonSachActionPerformed(evt);
            }
        });

        jbtThanhToan.setText("Thanh toán");
        jbtThanhToan.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtThanhToanActionPerformed(evt);
            }
        });

        jbtThoat.setText("Thoát");
        jbtThoat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtThoatActionPerformed(evt);
            }
        });

        jbtHuy.setText("Hủy");
        jbtHuy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtHuyActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel3))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jtfTenNhanVien, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)
                                    .addComponent(jtfTongTien))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jtfNgayLapHD))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(119, 119, 119)
                        .addComponent(jbtChonSach)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jbtThanhToan)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jbtHuy)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jbtThoat)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtChonSach, jbtHuy, jbtThanhToan, jbtThoat});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jtfTenNhanVien, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jtfNgayLapHD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtfTongTien, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtChonSach)
                    .addComponent(jbtThanhToan)
                    .addComponent(jbtThoat)
                    .addComponent(jbtHuy))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtChonSachActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtChonSachActionPerformed
        ChonSach c = new ChonSach(this, gioHang, true);
        c.setTitle("Chọn sách");
        c.setVisible(true);
    }//GEN-LAST:event_jbtChonSachActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String ngay = dateFormat.format(date);
        this.jtfNgayLapHD.setText(ngay);
    }//GEN-LAST:event_formWindowOpened

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        float tongTien = 0;
        DefaultTableModel dm = (DefaultTableModel) this.jtblSach.getModel();
        for (int i = dm.getRowCount() - 1; i >= 0; i--) {
            dm.removeRow(i);
        }
        for (int i = 0; i < gioHang.size(); i++) {
            Sach s = gioHang.get(i);
            float thanhTien = s.getSoLuongBan() * s.getGiaBan();
            tongTien = tongTien + thanhTien;

            Vector vt = new Vector();
            vt.add(i);
            vt.add(s.getMaSach());
            vt.add(s.getTenSach());
            vt.add(s.getGiaBan());
            vt.add(s.getSoLuongBan());
            vt.add(thanhTien);

            this.tableModel.addRow(vt);
        }

        this.jtfTongTien.setText("" + tongTien);
    }//GEN-LAST:event_formWindowActivated

    private void jbtThoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtThoatActionPerformed
        this.dispose();
    }//GEN-LAST:event_jbtThoatActionPerformed

    private void jbtHuyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtHuyActionPerformed
        float tongTien = 0;
        DefaultTableModel dm = (DefaultTableModel) this.jtblSach.getModel();
        for (int i = dm.getRowCount() - 1; i >= 0; i--) {
            dm.removeRow(i);
        }

        this.jtfTongTien.setText("" + tongTien);
    }//GEN-LAST:event_jbtHuyActionPerformed

    private void jbtThanhToanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtThanhToanActionPerformed

        boolean kq = false;
        HoaDon hd = new HoaDon();
        hd.setNgayLapHoaDon(this.jtfNgayLapHD.getText());
        hd.setTenNhanVien(this.jtfTenNhanVien.getText());
        hd.setTongTien(Float.parseFloat(this.jtfTongTien.getText()));

        int maHoaDonNew = port.themHoaDon(hd);
        if (maHoaDonNew == 0) {
            JOptionPane.showMessageDialog(this, "Xuất hóa đơn thất bại. Xin vui lòng thực hiện lại", "Xuất hóa đơn", JOptionPane.ERROR_MESSAGE);
        } else {
            for (Sach sach : gioHang) {
                ChiTietHoaDon cthd = new ChiTietHoaDon();
                cthd.setMaHoaDon(maHoaDonNew);
                cthd.setMaSach(sach.getMaSach());
                cthd.setSoLuongBan(sach.getSoLuongBan());
                cthd.setGiaBan(sach.getGiaBan());

                kq = port.themChiTietHoaDon(cthd);

                if (kq == true) {
                    JOptionPane.showMessageDialog(this, "Xuất hóa đơn thành công.\nXin quí khách vui lòng kiểm tra và trả tiền", "Xuất hóa đơn", JOptionPane.INFORMATION_MESSAGE);

                } else {
                    JOptionPane.showMessageDialog(this, "Xuất hóa đơn thất bại. Xin vui lòng thực hiện lại", "Xuất hóa đơn", JOptionPane.ERROR_MESSAGE);
                }
            }
        }



    }//GEN-LAST:event_jbtThanhToanActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(HoaDonBanSach.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(HoaDonBanSach.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(HoaDonBanSach.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(HoaDonBanSach.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                HoaDonBanSach dialog = new HoaDonBanSach(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtChonSach;
    private javax.swing.JButton jbtHuy;
    private javax.swing.JButton jbtThanhToan;
    private javax.swing.JButton jbtThoat;
    private javax.swing.JTable jtblSach;
    private javax.swing.JTextField jtfNgayLapHD;
    private javax.swing.JTextField jtfTenNhanVien;
    private javax.swing.JTextField jtfTongTien;
    // End of variables declaration//GEN-END:variables
}
